/**
 * Copyright 2010 Creative Works, Inc.
 * Creative Works licenses this file to you under the Apache License, version
 * 2.0 (the "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *    http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.sendvox.freswitch.inbound.impl;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.sendvox.freswitch.core.Command;
import org.sendvox.freswitch.event.impl.RawMessage;
import org.sendvox.freswitch.util.Arguments;

public class AuthenticationChannelHandler extends InboundChannelHandler
		implements Closeable {

	private static final Logger logger = Logger
			.getLogger(AuthenticationChannelHandler.class.getName());

	public final AtomicBoolean isAuthenticated = new AtomicBoolean(false);

	public static final String MESSAGE_TERMINATOR = "\n\n";

	private static final String SPACE = " ";

	private Channel channel;

	protected void authenticationRequest(String cs) {
		logger.log(Level.INFO, "Auth requested, sending [auth *******]");
		Arguments.INSTANCE.validate(cs).isNotNull().isNotEmpty();
		String authCmd = Command.AUTH.getName().concat(SPACE).concat(cs);
		RawMessage rawMsg = executeSyncCommand(channel, authCmd);

		if (rawMsg.getHeaders().containsValue(
				ResponseCallbacks.Value.OK.getLiteral())) {
			logger.log(Level.INFO, "User authenticated!");
			isAuthenticated.set(true);
		}

	}

	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		channel = e.getChannel();
		super.channelOpen(ctx, e);
	}

	public void close() throws IOException {
		channel.close().awaitUninterruptibly();
	}

}
